import Vue from "vue";
import VueRouter from "vue-router";
import { UIplugins } from "../common/UIplugins";
import { store } from "../store";
import TabBar from "../views/TabBar.vue";
import Home from "../views/Home.vue";
import ApplyList from "../views/ApplyList.vue";
import Process from "../views/Process.vue";
import Profile from "../views/Profile.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "tabBar",
    component: TabBar,
    children: [
      {
        path: "",//（空的子路由）当path: "/"时候，直接匹配显示该component内容
        name: "home",
        component: Home
      },
      {
        path: "/applyList",
        name: "applyList",
        component: ApplyList
      },
      {
        path: "/process",
        name: "process",
        component: Process,
        meta:{requireAuth: true }
      },
      {
        path: "/profile",
        name: "profile",
        component: Profile,
        meta:{requireAuth: true }
      }
    ]
  },
  {
    path: "/debugSetting",
    name: "debugSetting",
    component: () => import("../views/DebugSetting.vue"),
  }
];

// 获取当前文件夹下的js文件列表并加入到routes数组
const files = require.context('.', false, /\.js$/);
files.keys().forEach(key => {
  if(key.indexOf('index') < 0){
    //routes.concat(files(key).default);
    routes.push(...files(key).default);
  }
});

const router = new VueRouter({
  routes
});

router.beforeEach((to, from, next) => { // 路由导航守卫
	//console.log('from:', from, 'to:', to)
  function requireAuth(){ // 判断是否需要登录验证的页面
    return new Promise(function(resolve, reject) {
      if(to.meta.requireAuth) {
        if (store.getters.getToken != '') 
          resolve();
        else 
          reject({
            path: '/login', 
            mess: '未登录 或 登陆信息失效，请重新登陆'
          });
      }else resolve();
    });
  }
  // 开始验证
  requireAuth().then( ()=> {
    next();
  }).catch( (data)=> {
    console.log(data);
    if(data.path == '/login'){
			store.commit('updateToken', '');
			// console.log(store.getters['user/getUserInfo'])
			store.commit('user/updateUserInfo', {});
      UIplugins.message({message: data.mess, type: 'error'});
      router.push({ // 正常服务器下使用next会出现Uncaught (in promise)？？？
        path: '/login',
        query: {redirect: to.fullPath}  //从哪个页面跳转
      });
      /* next({
        path: '/login',
        query: {redirect: to.fullPath}  //从哪个页面跳转
      }); */
    }else next(data.path);
  });
});

export default router;
